<style>
    .model-form .layui-form-label {
        width: 100px;
    }
    .model-form .layui-input-block {
        margin-left: 130px;
    }
    .import {
        opacity: 0;
        position: absolute;
        width: 69px;
        height: 38px;
        margin-left: -20px;
        cursor: pointer;
    }
    xm-select > .xm-body .scroll-body{
        max-height: 220px;
    }
</style>
<!-- 正文开始 -->
<div class="layui-fluid">
    <div class="layui-card">
        <div class="layui-card-body">
            <!-- 头部操作栏 -->
            <div class="layui-form lay-header">
                <div class="toolbar">
                    <div class="layui-form-item lay-query-content">
                        <div class="lay-query-box">
                            <div class="query-lt">
                                <div class="layui-inline">
                                    <label class="layui-form-label w-auto">企业名称：</label>
                                    <div class="layui-input-inline">
                                        <select name="companyInfoId" class="common-select-search"></select>
                                    </div>
                                </div>
                                <div class="layui-inline">
                                    <label class="layui-form-label w-auto">是否终级部门：</label>
                                    <div class="layui-input-inline">
                                        <select name="isFinal" class="common-select-search">
                                            <option value="">请选择</option>
                                            <option value="0">否</option>
                                            <option value="1">是</option>
                                        </select>
                                    </div>
                                </div>
                                <div class="layui-inline">
                                    <label class="layui-form-label w-auto">名称：</label>
                                    <div class="layui-input-inline">
                                        <input name="name" class="layui-input" type="text" placeholder="请输入名称" autocomplete="off" />
                                    </div>
                                </div>
                                <div class="layui-inline">
                                    <label class="layui-form-label w-auto">负责人：</label>
                                    <div class="layui-input-inline">
                                        <input name="principalName" class="layui-input" type="text" placeholder="请输入负责人" autocomplete="off"/>
                                    </div>
                                </div>
                            </div>
                            <div class="query-rt">
                                <div class="layui-inline">
                                    <button class="layui-btn icon-btn color-green" lay-filter="formSubSearchLog" lay-submit layui-form-keyDownSearch="true">查询</button>
                                    <button class="layui-btn icon-btn color-white" lay-filter="resets" lay-submit>重置</button>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="lay-btn-rows">
                    <div class="lay-btn-box">
                        <div class="lay-btn-lt">
                            <button id="departmentBtnAdd" class="layui-btn icon-btn color-reseda">添加</button>
                            <button id="departmentBtnImport" class="layui-btn icon-btn color-reseda">
                                <input id="uploaderInput" type="file" name="file" class="import" accept=".xls,.xlsx" style="cursor: pointer"/>导入
                            </button>
                        </div>
                        <div class="lay-btn-rt">
                            <button id="departmentBtnTemplate" class="layui-btn icon-btn color-green">模板下载</button>
                            <button id="departmentBtnExport" class="layui-btn icon-btn color-green">导出</button>
                        </div>
                    </div>
                </div>
            </div>
            <!-- 表格 -->
            <table class="layui-table" id="departmentTable" lay-filter="departmentTable"></table>
        </div>
    </div>
</div>

<!-- 表格操作列 -->
<script type="text/html" id="departmentTableBar">
    <a class="layui-btn layui-btn-primary layui-btn-xs" lay-event="edit">修改</a>
    <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
</script>

<!-- 表单弹窗 -->
<script type="text/html" id="departmentForm">
    <form lay-filter="departmentForm" class="layui-form model-form">
        <input name="id" type="hidden"/>
        <div class="layui-form-item">
            <label class="layui-form-label"><span style="color: red">*</span>企业</label>
            <div class="layui-input-block">
                <select name="companyInfoId" lay-filter="getCompanyInfo" lay-verify="required" required></select>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">上级部门</label>
            <!--<div class="layui-input-block">
                <select name="parentId"></select>
            </div>-->
            <input name="parentId" type="hidden"/>
                <div class="layui-input-block" id="selectCategory">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label"><span style="color: red">*</span>名称</label>
            <div class="layui-input-block">
                <input name="name" placeholder="请输入名称" type="text" class="layui-input" maxlength="200" lay-verify="required|isOnlyName" required autocomplete="off"/>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label"><span style="color: red">*</span>编码</label>
            <div class="layui-input-block">
                <input name="code" placeholder="请输入编码" type="text" class="layui-input" maxlength="200" lay-verify="required|isOnlyCode" required autocomplete="off"/>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label"><span style="color: red">*</span>成本中心</label>
            <div class="layui-input-block">
                <input name="costCenter" placeholder="请输入成本中心" type="text" class="layui-input" maxlength="200" lay-verify="required|isOnlyCostCenter" required autocomplete="off"/>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">负责人</label>
            <div class="layui-input-block">
                <select name="principal"></select>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label"><span style="color: red">*</span>是否终级部门</label>
            <div class="layui-input-block">
                <input name="isFinal" type="checkbox" lay-skin="switch" value="0" lay-text="是|否"/>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label"><span style="color: red">*</span>是否启用</label>
            <div class="layui-input-block">
                <input name="isDeleted" type="checkbox" lay-skin="switch" value="1" checked="false" lay-text="启用|停用"/>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">备注描述</label>
            <div class="layui-input-block">
                <input name="remark" placeholder="请输入备注描述" type="text" maxlength="200" class="layui-input" autocomplete="off"/>
            </div>
        </div>
        <!--<div class="layui-form-item">
            <label class="layui-form-label">排序</label>
            <div class="layui-input-block">
                <input name="sortNumber" placeholder="请输入排序" type="text" maxlength="10" class="layui-input" />
            </div>
        </div>-->
        <div class="layui-form-item text-right">
            <button class="layui-btn layui-btn-primary" type="button" ew-event="closeDialog">取消</button>
            <button class="layui-btn" lay-filter="departmentFormSubmit" lay-submit>保存</button>
        </div>
    </form>
</script>

<!-- js部分 -->
<script type="text/javascript" src="../../../admin/assets/js/jsencrypt.min.js"></script>
<script>
    layui.use(['layer', 'form', 'table', 'admin', 'tableTreeDj'], function () {
        var $ = layui.jquery;
        var layer = layui.layer;
        var form = layui.form;
        var table = layui.table;
        var config = layui.config;
        var admin = layui.admin;
        var upload = layui.upload;
        var tableTree = layui.tableTreeDj;

        admin.selectSearch();  //下拉选中调用搜索
        // 获取企业数据
        admin.req('user/admin/companyInfo/list', {limit:9999}, function (res) {
            if ( res.code==200) {
                var html='<option value="">请选择企业</option>';
                for(var k=0;k<res.data.length;k++){
                    html+='<option value="'+res.data[k].id+'">'+res.data[k].name+'</option>';
                }
                $("select[name='companyInfoId']").html(html);
                form.render('select')
            } else {
                layer.msg('获取企业失败', {icon: 2, time: 1000});
            }
        }, 'GET');

        // 渲染表格
        var insTb = tableTree.render({
            id: '#departmentTable',
            elem: '#departmentTable',
            url: config.base + 'user/admin/department/list',
            toolbar: true,
            defaultToolbar: ["filter"],
            where: {limit: 999},
            page: false,
            cellMinWidth: 120,
            cols: [[
                {type: 'numbers', title: '序号', fixed: 'left'}
                ,{field: 'name', sort: true, title: '名称', fixed: 'left'}
                ,{field: 'code', sort: true, title: '编码'}
                ,{field: 'costCenter', title: '成本中心'}
                ,{field: 'companyInfoName', sort: true, title: '企业名称'}
                ,{field: 'parentName', sort: true, title: '上级部门'}
                ,{field: 'isFinal', sort: true, title: '是否终级部门', templet: function (d) {
                        return d.isFinal ? "是" : "否";
                    }}
                ,{field: 'principalName', sort: true, title: '负责人'}
                ,{field: 'createTime', sort: true, title: '创建时间'}
                ,{align: 'center', toolbar: '#departmentTableBar', title: '操作', width: 200, fixed: 'right'}
            ]],
            done: function (res, curr, count) {
                //移除按钮
                var menuButton = config.getMenuButton(location.hash);
                if(menuButton.indexOf("搜索") == -1){
                    $('.layui-form.toolbar').remove();
                }
                if(menuButton.indexOf("修改") == -1){
                    $("[lay-event='edit']").remove();
                }
                if(menuButton.indexOf("删除") == -1){
                    $("[lay-event='del']").remove();
                }
            }
        }, {keyPid: "parentId", title: "name"});

        // 工具条点击事件
        table.on('tool(departmentTable)', function (obj) {
            var data = obj.data;
            if (obj.event === 'edit') { //修改
                showEditModel(data, data.parentId);
            } else if (obj.event === 'del') { // 删除
                doDelete(obj);
            }
        });

        //监听排序
        table.on('sort(departmentTable)', function(obj){
            table.reload('departmentTable', {
                initSort: obj
                ,where: {
                    sort: obj.field
                    ,order: obj.type
                }
            });
        });

        // 搜索
        form.on('submit(formSubSearchLog)', function (data) {
            insTb.reload({where: data.field},'data');
        });

        // 重置搜索
        form.on('submit(resets)', data => {
            insTb.reload({where: admin.resetSearch(data.field), page: {curr: 1}}, 'data');
        });

        // 添加按钮点击事件
        $('#departmentBtnAdd').click(function () {
            showEditModel();
        });

        // 显示编辑弹窗
        function showEditModel(data, parentIdVal) {
            let finalCategoryIds = [];
            admin.open({
                type: 1,
                area: '720px',
                offset: '65px',
                title: data ? '修改部门架构' : '添加部门架构',
                content: $('#departmentForm').html(),
                success: function () {
                    function treeEach(treeData, ids) {
                        $.each(treeData, function (i, val) {
                            if (customContains(ids, val.value)) {
                                val.disabled = true;
                            }
                            if (val.children && val.children.length > 0) {
                                treeEach(val.children, ids);
                            }
                        });
                    }

                    function filterDepartmentData(treeData, companyInfoId) {
                        var list = [];
                        $.each(treeData, function (i, val) {
                            if (companyInfoId == val.companyInfoId) {
                                list.push(val);
                            }
                        });
                        return list;
                    }

                    let customContains = function (box, val) {
                        for (let i = 0; i < box.length; i++) {
                            if (box[i] == val) {
                                return true;
                            }
                        }
                        return false;
                    };

                    form.verify({
                        isOnlyCode: function (value) {
                            var isOnly = true;
                            var idVal = $("form input[name='id']").val();
                            admin.req('user/admin/department/isOnly', {code:value,id:idVal}, function (res) {
                                if (res.code == 200) {
                                    isOnly = res.data;
                                }
                            }, 'GET',false);
                            if(!isOnly){
                                return "编码必须唯一"
                            }
                        }
                    })
                    form.verify({
                        isOnlyCostCenter: function (value) {
                            var isOnly = true;
                            var idVal = $("form input[name='id']").val();
                            admin.req('user/admin/department/isOnlyCostCenter', {costCenter:value,id:idVal}, function (res) {
                                if (res.code == 200) {
                                    isOnly = res.data;
                                }
                            }, 'GET',false);
                            if(!isOnly){
                                return "成本中心必须唯一"
                            }
                        }
                    })
                    form.verify({
                        isOnlyName: function (value) {
                            var isOnly = true;
                            var idVal = $("form input[name='id']").val();
                            var companyInfoId = $("form input[name='companyInfoId']").val();
                            admin.req('user/admin/department/isOnlyName', {companyInfoId:companyInfoId,name:value,id:idVal}, function (res) {
                                if (res.code == 200) {
                                    isOnly = res.data;
                                }
                            }, 'GET',false);
                            if(!isOnly){
                                return "部门名称必须唯一"
                            }
                        }
                    })

                    // 获取企业数据
                    admin.req('user/admin/companyInfo/list', {limit:9999}, function (res) {
                        if ( res.code==200) {
                            var html='<option value="">请选择企业</option>';
                            for(var k=0;k<res.data.length;k++){
                                html+='<option value="'+res.data[k].id+'">'+res.data[k].name+'</option>';
                            }
                            $("form select[name='companyInfoId']").html(html);
                            form.render('select');
                            if(data && data.companyInfoId){
                                form.val('departmentForm', data);
                            }
                            form.on('select(getCompanyInfo)', function (data) {
                                if(data.value){
                                    // 获取上级部门
                                    getParentData(data.value);
                                }else{
                                    $("form select[name='companyInfoId']").html("");
                                }
                            })
                        } else {
                            layer.msg('获取企业失败', {icon: 2, time: 1000});
                        }
                    }, 'GET');

                    // 获取部门数据
                    admin.req('user/admin/department/list', {limit:9999}, function (res) {
                        if ( res.code==200) {
                            var html='<option value="">顶级部门</option>';
                            for(var k=0;k<res.data.length;k++){
                                html+='<option value="'+res.data[k].id+'">'+res.data[k].name+'</option>';
                            }
                            $("form select[name='parentId']").html(html);
                            form.render('select');
                            if(data && data.principal){
                                form.val('departmentForm', data);
                            }
                        } else {
                            layer.msg('获取部门失败', {icon: 2, time: 1000});
                        }
                    }, 'GET');

                    getParentData();

                    function getParentData(companyInfoId){
                        xmSelect.render({
                            el: '#selectCategory',
                            model: {label: {type: 'text'}},
                            radio: true,
                            clickClose: true,
                            filterable: true,
                            tree: {
                                show: true,
                                strict: false,
                                /*expandedKeys: [-1],*/
                                expandedKeys: true,
                            },
                            tips: '顶级部门',
                            height: 'auto',
                            data() {
                                if (parentIdVal != undefined) {
                                    $("input[name='parentId']").val(parentIdVal);
                                }
                                let treeData = tableTree.getTree(data && parentIdVal == undefined ? data.parentId : parentIdVal, data ? data.id : null);
                                if (finalCategoryIds != null && finalCategoryIds.length > 0) {
                                    treeEach(treeData, finalCategoryIds);
                                }
                                if(companyInfoId){
                                    treeData = filterDepartmentData(treeData, companyInfoId);
                                }
                                return treeData;
                            },
                            on: function (data) {
                                //被选中的select的id,如果没有 -1
                                let parentId = data.arr.length > 0 ? data.change[0].value : -1;
                                $("input[name='parentId']").val(parentId);
                            },
                        });
                    }

                    //data 非空取值names
                    if (!config.isEmptyObject(data)) {
                        data.name = data.name.indexOf("</span>") > 0 ? data.name.split("</span>")[1] : data.name;
                        data.name = data.name.indexOf("&nbsp; &nbsp;") > 0 ? data.name.split(" &nbsp; &nbsp;").length>2?data.name.split(" &nbsp; &nbsp;")[2]:data.name.split(" &nbsp; &nbsp;")[1] : data.name;
                    }

                    // 获取人员数据
                    admin.req('user/admin/user/list', {limit:9999}, function (res) {
                        if ( res.code==200) {
                            var html='<option value="">请选择负责人</option>';
                            for(var k=0;k<res.data.length;k++){
                                html+='<option value="'+res.data[k].id+'">'+res.data[k].username+'|'+res.data[k].nickname+'</option>';
                            }
                            $("form select[name='principal']").html(html);
                            form.render('select');
                            if(data && data.principal){
                                form.val('departmentForm', data);
                            }
                        } else {
                            layer.msg('获取人员失败', {icon: 2, time: 1000});
                        }
                    }, 'GET');

                    form.val('departmentForm', data);

                    // 表单提交事件
                    form.on('submit(departmentFormSubmit)', function (d) {
                        layer.load(2);
                        var isDeleted=$("form input[name='isDeleted']").prop("checked");
                        if(!isDeleted){
                            d.field.isDeleted=false;
                        }else{
                            d.field.isDeleted=true;
                        }
                        var isFinal=$("form input[name='isFinal']").prop("checked");
                        if(!isFinal){
                            d.field.isFinal=false;
                        }else{
                            d.field.isFinal=true;
                        }
                        admin.req(data ? 'user/admin/department/update' : 'user/admin/department/add', d.field, function (res) {
                            layer.closeAll('loading');
                            if (res.code == 200) {
                                layer.msg(res.msg, {icon: 1});
                                insTb.reload('departmentTable');
                                layer.closeAll('page');
                            } else {
                                layer.msg(res.msg, {icon: 2});
                            }
                        }, data ? 'PUT' : 'POST');
                        return false;
                    });
                }
            });
        }

        // 删除
        function doDelete(obj) {
            layer.confirm('确定要删除吗？', {
                offset: '65px',
                skin: 'layui-layer-admin'
            }, function (i) {
                layer.close(i);
                layer.load(2);
                admin.req('user/admin/department/' + obj.data.id, {}, function (res) {
                    layer.closeAll('loading');
                    if (res.code == 200) {
                        layer.msg(res.msg, {icon: 1});
                        obj.del();
                    } else {
                        layer.msg(res.msg, {icon: 2});
                    }
                }, 'DELETE');
            });
        }
        
        // 模板下载
        $("#departmentBtnTemplate").click(function () {
            window.location.href = config.base + "user/admin/department/template";
        })

        // 导入excel
        $('#uploaderInput').on("change", function (e) {
            layer.load(2);
            var formData = new FormData();
            var files = e.target.files;
            let that = $(this);
            formData.append("file", files[0]);
            formData.append("name", files[0].name);//这个地方可以传递多个参数
            $.ajax({
                url: config.base + 'user/admin/department/importExcel',
                data: formData,
                headers: {Authorization: 'Bearer ' + config.getToken()},
                type: "POST",
                processData: false,
                contentType: false,
                success: function (res) {
                    layer.closeAll('loading');
                    if (res.code == 200) {
                        layer.msg(res.msg, {icon: 1});
                        layer.closeAll('page');
                        setTimeout(_ => {
                            location.reload()
                        }, 1000);
                    } else {
                        layer.msg(res.msg, {icon: 2});
                    }
                    that.val('');
                }
            });
        })

        // 导出excel
        $('#departmentBtnExport').click(function () {
            var publicKey = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCcLt6aJfWmRid+8Cuirv9Zi8sVfhSJ+pUkL7dC+M1yc+e6zr+PQj8sbl2jV5ZBhF4VwoIHWzFLoxNKSizukUNzumJi1KwhjmbASN2EVBKUhJwmx422oew9WCnZYE9+/T+xF87Diie3uQm+7cYVCpvlpqnf9zMBB0Js9zYjOPtP4wIDAQAB";
            var crypt = new JSEncrypt();
            crypt.setKey(publicKey);
            var token = "Bearer "+config.getToken();
            var tokenLeft = token.substring(0,50);
            var tokenRight = token.substring(50);
            var enc = crypt.encrypt(tokenLeft);
            var access_token = enc+tokenRight;
            access_token = access_token.replaceAll('+', '%2B');
            window.location.href = config.base + "user/admin/department/export?access_token=" + access_token;
        });

    });
</script>